# -*- coding: utf-8 -*-
from bopress.hook import add_menu_page, add_action
from bopress.orm import SessionFactory
from bopress.user import ObjectPermissionChecker, add_capability, remove_perms_for_bulk_delete
from bopress.utils import Utils
from userobjectermissionsdemo.model import Posts

plugin_name = "User Object Permissions Demo"
version = "1.0"
__author__ = 'yezang'

add_menu_page("User Object Permissions Demo", "User Object Permissions Demo",
              "user-object-permissions-demo", ["list_users"], "userobjectermissionsdemo/tpl/uop.html")


def delete_event_demo():
    s = SessionFactory.session(use_evt=True)
    try:
        s.query(Posts).filter(Posts.post_id == 6).delete()
        remove_perms_for_bulk_delete(s, Posts, [6])
        s.commit()
    except Exception as e:
        print(e)
        s.rollback()


def data(handler):
    # delete_event_demo()
    s = SessionFactory.session()
    p = Posts()
    p.title = "Configuration 1"
    p.content = "After installation we can prepare our project for object permissions handling. " \
                "In a settings module we need to add guardian to INSTALLED_APPS"
    p.pubdate = Utils.current_datetime()
    s.add(p)
    s.commit()
    # 角色权限
    chk = ObjectPermissionChecker()
    chk.assign(['r_edit_post', 'r_delete_post'], p)
    # 用户权限
    chk2 = ObjectPermissionChecker(2)
    chk2.assign(['add_post', 'list_post', 'edit_post', 'delete_post'], p)

    b1 = chk2.has_perms('edit_post', p)
    b2 = chk2.has_perms('edit_post', p, use_role=True)

    print(b1, b2)

    users = chk2.get_users(p)
    s = SessionFactory.session()
    r = s.query(users)
    print(r.value(users.c.user_id))

    chk2.remove_perms(["r_delete_post"], p, use_role=True)

    users_set = chk2.get_objects(["edit_post", "r_edit_post"], Posts)
    z = s.query(Posts.title, Posts.content) \
        .select_from(users_set).outerjoin(Posts, Posts.post_id == users_set.c.object_id) \
        .all()
    print(z)
    handler.render_json(p.post_id)


def init():
    add_capability("add_post", "Post", "新增文章")
    add_capability("list_post", "Post", "查看文章")
    add_capability("edit_post", "Post", "编辑文章")
    add_capability("delete_post", "Post", "删除文章")
    add_capability("r_edit_post", "Post", "修改文章")
    add_capability("r_delete_post", "Post", "移除文章")


add_action("bo_init", init)
add_action("bo_api_get_user_object_permissions_demo", data)
